import requests
import json

from plugins.common import settings

#健康请求测试
def rasa_core_health():
    url = settings.servers.resa_core.health_url
    try:
        response = requests.request("GET", url, timeout=1)
        data = json.loads(response.text)
        
        if data['status'] == 'ok':
            return 'yes'
        else:
            return 'no'
    except requests.exceptions.Timeout:
        return 'time out'
    except requests.exceptions.RequestException as e:
        return f"请求发生异常：{e}"
    
#获得意图
def intent_key(message):
    url = settings.servers.resa_intent.url
    try:
        payload = json.dumps({ "text": message,})
        headers = { 'Content-Type': 'application/json' }

        response = requests.request("POST", url, headers=headers, data=payload)
  
        data = json.loads(response.text)
        return data
    except requests.exceptions.Timeout:
        print("请求意图时间超时")
        return []
    except requests.exceptions.RequestException as e:
        print(f"请求意图发生异常：{e}")
        return []
 
#获得消息的意图key
def rasa_intent_key(message):
    data = intent_key(message)
    if len(data) > 0 and data['intent']['name'] :
        return data['intent']['name']
    else:
        return ''
    
def rasa_dialog(session_id, message, metadata={}):
    url = settings.servers.resa_core.url
    try:
        payload = json.dumps({ "sender": session_id, "message": message, "metadata": metadata})
        headers = { 'Content-Type': 'application/json' }

        response = requests.request("POST", url, headers=headers, data=payload)

        print('rasa 请求：' + payload )
        print('rasa 返回：' + response.text )
        data = json.loads(response.text)
        if len(data) <= 0 :
            print("rasa 返回空数据")
            return ''
        elif  'text' in data[0] :
            return data[0]['text']
        else:
            return ''
    except requests.exceptions.Timeout:
        print("请求意图时间超时")
        return ''
    except requests.exceptions.RequestException as e:
        print(f"请求意图发生异常：{e}")
        return ''